//
//  SALeftMenuController.m
//  ShopAssistant
//
//  Created by ZhaoYiding on 2017/11/18.
//  Copyright © 2017年 hyxt. All rights reserved.
//

#import "SALeftMenuController.h"
#import "SALeftMenuViewCell.h"
#import "SAMenuHeaderSectionView.h"
#import "SASettingController.h"
#import "XLSlideMenu.h"
#import "SALeftSelectedModel.h"
@interface SALeftMenuController ()<UITableViewDelegate,UITableViewDataSource>
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *data;
@end

@implementation SALeftMenuController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    [self buildUI];
    
    [self buildTableView];
    
    [self loadshopListData];
    
    [self buildSetting];
    
    
}



- (void)buildUI
{
    SALeftMenuViewCell * titleView = [[NSBundle mainBundle] loadNibNamed:@"SALeftMenuViewCell" owner:nil options:nil].lastObject;
    titleView.frame = CGRectMake(0, SA_CONTENT_START_Y - 34, self.view.width, 34);
    titleView.titleLabel.text = @"我的企业";
    titleView.imageView.image = [UIImage imageNamed:@"menu_letf_header"];
    [self.view addSubview:titleView];
}

- (void)buildTableView
{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, SA_CONTENT_START_Y, self.view.width, SA_SCREEN_HEIGHT - SA_CONTENT_START_Y - 70) style:UITableViewStyleGrouped];
    self.tableView.estimatedRowHeight = 0;
    self.tableView.estimatedSectionHeaderHeight = 0;
    self.tableView.estimatedSectionFooterHeight = 0;
    self.tableView.backgroundView = nil;
    self.tableView.backgroundColor = self.view.backgroundColor = SAHEXRGB(0xF2F2F2);
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    [self.tableView registerNib:[UINib nibWithNibName:@"SALeftMenuViewCell" bundle:nil] forCellReuseIdentifier:@"SALeftMenuViewCell"];
    [self.view addSubview:self.tableView];
}

- (void)buildSetting
{
    UIView *settingView = [[UIView alloc] initWithFrame:CGRectMake(0,self.view.height - 70, self.view.width, 70)];
    
    [self.view addSubview:settingView];
    
    UIImageView * iconImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"menu_setting"]];
    [settingView addSubview:iconImageView];
    [iconImageView sizeToFit];
    iconImageView.left = 20;
    iconImageView.centerY = 35;
    
    UILabel *titleLabel = [[UILabel alloc] init];
    titleLabel.text = @"设置";
    titleLabel.font = [UIFont systemFontOfSize:18.0];
    [settingView addSubview:titleLabel];
    [titleLabel sizeToFit];
    titleLabel.left = iconImageView.right + 10;
    titleLabel.centerY = 35;
    
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tapAction)];
    [settingView addGestureRecognizer:tap];
}

- (void)loadshopListData
{
    [SAHttpApi requestListWithPhone:[SAUserDefaults objectForKey:@"SAPhone"] WithComeBack:^(NSDictionary *object, NSError *error) {
        if (!error)
        {
            if ([object[@"status"] integerValue] == 1)
            {
                self.data = [NSMutableArray array];
                NSInteger i = 0;
                for (NSDictionary *dict in object[@"content"])
                {
                    SALeftSelectedModel *model = [[SALeftSelectedModel alloc] init];
                    model.shopName = dict[@"shopName"];
                    model.shopId = dict[@"shopId"];
                    if ([model.shopId isEqualToString:[SAUserInfoManager sharedSAUserInfoManager].model.shopId])
                    {
                        model.indexPath = [NSIndexPath indexPathForRow:[SAUserInfoManager sharedSAUserInfoManager].model.row?[SAUserInfoManager sharedSAUserInfoManager].model.row - 1:0 inSection:i];
                    }
                    [self.data addObject:model];
                    i++;
                }
                [self.tableView reloadData];
            }
            else
            {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:object[@"msg"]];
            }
        }
        else
        {
            [MBProgressHUD hideHUD];
            [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
        }
        
    }];
}

#pragma mark - UITableViewDelegate,UITableViewDataSource

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    SALeftSelectedModel *model = self.data[section];
    if (model.isSelected)
    {
        return model.arr.count;
    }
    return 0;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return self.data.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    SALeftMenuViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"SALeftMenuViewCell"];
    
    SALeftSelectedModel *model = self.data[indexPath.section];
    cell.titleLabel.text = model.arr[indexPath.row];
    
    if (indexPath.row == 0&&model.arr.count == 2)
    {
        cell.imageView.image = [UIImage imageNamed:@"shop_group"];
    }
    else
    {
        cell.imageView.image = [UIImage imageNamed:@"shop_work"];
    }
    
    if (model.isSelected)
    {
        if (model.indexPath.row == indexPath.row && model.indexPath != nil)
        {
            cell.titleLabel.textColor = SAHEXRGB(0xE53546);
            if (indexPath.row == 0 && model.arr.count == 2)
            {
                cell.imageView.image = [UIImage imageNamed:@"shop_group_selected"];
            }
            else
            {
                cell.imageView.image = [UIImage imageNamed:@"shop_work_selected"];
            }
        }
        else
        {
            cell.titleLabel.textColor = SAHEXRGB(0x666666);
            if (indexPath.row == 0 && model.arr.count == 2)
            {
                cell.imageView.image = [UIImage imageNamed:@"shop_group"];
            }
            else
            {
                cell.imageView.image = [UIImage imageNamed:@"shop_work"];
            }
            
        }
        
    }
    
    
    return cell;
}

-(void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [MBProgressHUD showMessage:@"请稍候..."];
    SALeftSelectedModel *model = self.data[indexPath.section];
    
    NSString *string = @"";
    if (model.arr.count == 2)
    {
        if (indexPath.row == 0)
        {
            string = @"1";
        }
        else
        {
            string = @"2";
        }
    }
    else
    {
        string = @"2";
    }
    
    [SAHttpApi requestGetHTTPURLWithNumber:string WithEmpId:model.model._id WithAppTo:[model.model.identityCollect isEqualToString:@"1"]?@"2":@"1"  WithComeBack:^(NSDictionary *object, NSError *error) {
        if (!error)
        {
            
            if ([object[@"status"] integerValue] == 1)
            {
                [MBProgressHUD hideHUD];
                
                model.indexPath = indexPath;
                for (SALeftSelectedModel *selectedModel in self.data)
                {
                    if (model == selectedModel)
                    {
                        continue;
                    }
                    selectedModel.indexPath = nil;
                }
                [SAUserInfoManager sharedSAUserInfoManager].model = model.model;
                [SAUserDefaults setObject:@(indexPath.row + 1) forKey:model.shopId];
                [SAUserInfoManager sharedSAUserInfoManager].model.row = indexPath.row + 1;
                [[SAUserInfoManager sharedSAUserInfoManager] saveLoginInfo];
                [SAUserDefaults setObject:model.shopId forKey:@"SAShopId"];
                
                [self.tableView reloadData];
                [self.xl_sldeMenu showRootViewControllerAnimated:YES];
                
                [[NSNotificationCenter defaultCenter] postNotificationName:@"webViewReload" object:object];
            }
            else
            {
                [MBProgressHUD hideHUD];
                [MBProgressHUD showError:object[@"msg"]];
                
            }
        }
        else
        {
            [MBProgressHUD hideHUD];
            [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
        }
    }];
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    SAMenuHeaderSectionView *headerView = [[NSBundle mainBundle] loadNibNamed:@"SAMenuHeaderSectionView" owner:nil options:nil].lastObject;
    headerView.frame = CGRectMake(0, 0, self.view.width, 70);
    SALeftSelectedModel *model = self.data[section];
    headerView.titleLabel.text = model.shopName;
    if (model.indexPath.section == section&&model.isSelected)
    {
        headerView.lightView.hidden = NO;
        headerView.arrowImageView.image = [UIImage imageNamed:@"menu_arrow_up"];
        //        headerView.titleLabel.textColor = SAHEXRGB(0xE53546);
    }
    else
    {
        headerView.lightView.hidden = YES;
        headerView.arrowImageView.image = [UIImage imageNamed:@"menu_arrow_dowm"];
        //        headerView.titleLabel.textColor = SAHEXRGB(0x666666);
    }
    
    SAWeakSelf
    [headerView.actionBtn handleControlEvent:UIControlEventTouchUpInside withBlock:^{
        SAStrongSelf
        if (model.model)
        {
            model.isSelected = !model.isSelected;
            for (SALeftSelectedModel *selectedModel in self.data)
            {
                if (model == selectedModel)
                {
                    continue;
                }
                selectedModel.isSelected = NO;
            }
            
            [strongSelf.tableView reloadData];
            return ;
        }
        [MBProgressHUD showMessage:@"请稍候..."];
        [SAHttpApi requestGetUserInfoWithPhone:[SAUserDefaults objectForKey:@"SAPhone"] WithShopId:model.shopId WithComeBack:^(NSDictionary *object, NSError *error) {
            if (!error)
            {
                [MBProgressHUD hideHUD];
                if ([object[@"status"] integerValue] == 1)
                {
                    SAUserInfoModel *infoModel = [SAUserInfoModel mj_objectWithKeyValues:object[@"content"]];
                    
                    infoModel._id = object[@"content"][@"id"];
                    
                    model.model = infoModel;
                    
                    if ([infoModel.identityCollect isEqualToString:@"1"])
                    {
                        model.arr = @[@"我的工作台"];
                    }
                    else
                    {
                        model.arr = @[@"店员工作台",@"店长工作台"];
                    }
                    
                    model.isSelected = !model.isSelected;
                    
                    for (SALeftSelectedModel *selectedModel in self.data)
                    {
                        if (model == selectedModel)
                        {
                            continue;
                        }
                        selectedModel.isSelected = NO;
                    }
                    [self.tableView reloadData];
                }
                else
                {
                    
                    [MBProgressHUD showError:object[@"msg"]];
                    
                }
            }
            else
            {
                [MBProgressHUD hideHUD];
                [UIAlertView showWithTitle:@"提示" message:@"请检查网络设置,稍后再试.." cancelButtonTitle:nil otherButtonTitles:@[@"我知道了"] tapBlock:nil];
                
            }
        }];
    }];
    
    return headerView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 70;
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 0.1;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 70;
}

#pragma mark - Action

- (void)tapAction
{
    [self.xl_sldeMenu showRootViewControllerAnimated:YES];
    SASettingController *vc = [[SASettingController alloc] init];
    UINavigationController *nav = (UINavigationController *)self.xl_sldeMenu.rootViewController;
    [nav pushViewController:vc animated:YES];
}

@end
